home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 2279 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.1 KB

  1. Path: oxy.rust.net!usenet
  2. From: ebennett@rust.net
  3. Newsgroups: comp.lang.c
  4. Subject: Re: quick decision: is n a power of 2?
  5. Date: Sat, 20 Jan 1996 05:00:30 GMT
  6. Organization: Rust Net - High Speed Internet in Detroit  810-642-2276
  7. Message-ID: <4dpian$gij@oxy.rust.net>
  8. References: <Pine.OSF.3.91.960119114608.18779E-100000@io.UWinnipeg.ca>
  9. NNTP-Posting-Host: liv-12.rust.net
  10. X-Newsreader: Forte Free Agent 1.0.82
  11.  
  12. Bill Simpson <wsimpson@uwinnipeg.ca> wrote:
  13.  
  14. >Is there a fast way to decide whether a number n is a power of 2?
  15.  
  16.  
  17. Working with positive numbers, a number will be a power of 2 if there
  18. is exactly one bit set in the number.  (For negative numbers, you can
  19. use the following by taking the abs() of the number).
  20.  
  21. Given some number, there is a neat trick to generate a mask which will
  22. have exactly one bit set in it.  The bit set will be the least
  23. significant non-zero bit in the original number:
  24.  
  25.     mask = ~number & number;
  26.  
  27. Now, if number contained a single non-zero bit (and is therefore a
  28. power of 2),  mask will be equal to number.  Therefore:
  29.  
  30.    if (number == (~number & number))
  31.    {
  32.         /* number is a power of 2 */
  33.    }
  34.  
  35. Try it, you'll like it!
  36.  
  37. Earl
  38.  
  39.  
  40.